// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables
import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:junyeyishu/ui/home/widgets/QGTypeSwitchWidget.dart';
import 'package:junyeyishu/ui/sale/widgets/QGDrawerWidget.dart';
import 'package:junyeyishu/ui/sale/widgets/QGSortPriceWidget.dart';
import 'package:junyeyishu/ui/sale/widgets/QGSwitchWidget.dart';

import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:junyeyishu/widgets/QGListState.dart';

import 'widgets/QGSaleCell.dart';

class QGSalePage extends StatefulWidget {
  const QGSalePage({super.key});
  @override
  State<QGSalePage> createState() => _QGSalePageState();
}

class _QGSalePageState extends QGListState<QGSalePage> {
  int type = 0;
  int subtype = 1;
  int sorttype = 0;
  int leveltype = 0;
  int tabtype=1;

  List<String> names = [];

  var controller = TextEditingController();

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    eventBus.on<EventMainTabRefresh>().listen((event) {
      if (event.index != 1) return;
      onRefresh();
    });
    eventBus.on<EventLogin>().listen((event) {
      onSwitchType(type);
    });
    eventBus.on<EventRefreshTradeCategory>().listen((event) {
      onSwitchType(type);
    });

    tabURL = url_index_seriesList;

    gridDelegate = SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: 2,
      mainAxisSpacing: 15.rpx,
      crossAxisSpacing: 15.rpx,
      childAspectRatio: 165 / 254,
    );

      onSwitchType(type);

    Network.get(url_u_getMergedUserInfo).then((res) async {
      if (!res.success) {
        toast(res.msg);

        //处理token失效的情形
        if (!User.isLogin) {
          await Future.delayed(const Duration(seconds: 2));
          Navigator.of(context).pushNamed(PageLogin).then((value) {
            if (!User.isLogin) {
              eventBus.fire(EventMainTabSelectIndex(index: 0));
            }
          });
        }
        return;
      }

    
      // if (mounted) {
      //   setState(() {});
      // }

    });

  }

  @override
  tabParam() {
    var param = {};
    // 1衍生品，2版权品，3盲盒
    switch (type) {
      case 0:
        param['tab_type'] = 1;
        break;
      case 1:
        param['tab_type'] = 2;
        break;
      case 2:
        param['tab_type'] = 3;
        break;
    }

    return param;
  }

  @override
  listParam() {
    var param = tabParam();

    try {
      if (tab is List) {
        if (type == 0 && User.isLogin && subtype >= 1) {
          param['series_id'] = tab[subtype - 1]["id"];
        } else if (type == 0 && !User.isLogin && subtype >= 1) {
          param['series_id'] = tab[subtype - 1]["id"];
        }
      }
    } catch (e) {
      print(e);
    }

    if (type == 1 && sorttype < 2) {
      switch (sorttype) {
        case 0:
          param["price_sort"] = "asc";
          break;
        case 1:
          param["price_sort"] = "desc";
          break;
        default:
          break;
      }
    }

    if (type == 1 && sorttype == 2) {
      switch (leveltype) {
        case 1:
          param["level_id"] = 2;
          break;
        case 2:
          param["level_id"] = 3;
          break;
        case 3:
          param["level_id"] = 4;
          break;
        default:
          break;
      }
    }

    // param['key_word'] = controller.text;

    if (type == 0 && subtype == 0) {
      param['isRecommend'] = 1;
    }

    // if (type == 0 && subtype == 1) {
    //   param['isMe'] = 1;
    // }

    return param;
  }

  @override
  onUpdateTab(data) {
    names = [];
    if (type == 0) {
      // names = ["推荐"];
    }

    for (var item in data) {
      names.add(item["name"] ?? "");
    }

    if (mounted) {
      setState(() {});
    }
    onRefresh();
  }

  @override
  onUpdateList(data) {
    var temp = [];
    var ids = [];
    for (var item in data) {
      if (!ids.contains(item["id"])) {
        temp.add(item);
        ids.add(item["id"]);
      }
    }

    if (type == 1) {
      temp = temp.where((element) => element["onshelf_num"] > 0).toList();
    }

    list = temp;
    if (mounted) setState(() {});
  }

  @override
  Widget itemBuilder(context, index, data) {
    if (inReview()) {
      data?["nft_price"] = "888";
    }

    return GestureDetector(
        onTap: () {
          toDetail(data);
        },
        child: QGSaleCell(data: data, showLike: type == 0));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          unfocus(context);
        },
        child: Stack(
          children: [
            QGImage(
                asset: "sale_bg",
                width: kScreenWidth,
                height: 180.rpx + kNavHeight),
            Column(
              children: [
                 SizedBox(height: 15.rpx + max(20, kSafeTop)),
                Container(
                        alignment: Alignment.center,

                  margin: EdgeInsets.symmetric(horizontal: 15.rpx),
                  height: 40.rpx,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(25),
                    color: Color(0XFF0C1012)
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      SizedBox(width: 2.rpx,),
                      Expanded(
                        child: 
                        GestureDetector(
                          onTap: (){
                            tabtype =1;
                            onSwitchType(0);

                            // setState(() {
                              
                            // });
                          },
                          behavior: HitTestBehavior.opaque,
                          child: Container(
                         decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(25),
                        color: Color(tabtype==1? 0XFFFFFFFF:0XFF0C1012),
                        ),
                        alignment: Alignment.center,
                        height: 35.rpx,
                        child:Text('衍生品',style: TextStyle(fontSize: 16,color: Color(tabtype==1? 0XFF111111:0XFFFFFFFF),fontWeight: FontWeight.bold)),
                      ),
                        )
                      
                      ),
                       Expanded(child: 
                       GestureDetector(
                        onTap: (){
                            tabtype =3;
                            onSwitchType(2);
                            //  setState(() {
                              
                            // });
                          },
                          behavior: HitTestBehavior.opaque,
                        child: Container(
                           decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(25),
                        color: Color(tabtype==3? 0XFFFFFFFF:0XFF0C1012),
                        ),
                        alignment: Alignment.center,
                        height: 35.rpx,
                        child:Text('盲盒',style: TextStyle(fontSize: 16,color: Color(tabtype==3? 0XFF111111:0XFFFFFFFF),fontWeight: FontWeight.bold)),
                      ),
                       )
                      
                      ),
                      SizedBox(width: 2.rpx,),

                    ],
                  ),
                ),
                //  buildHeader(),
                SizedBox(height: 4.rpx),
                buildSwitchBar(),
                buildList(),
              ],
            ),
          ],
        ),
      ),
    );
  }

  buildHeader() {
    return Container(
      padding: EdgeInsets.only(bottom: 0.rpx),
      color: Colors.transparent,
      child: Column(
        children: [
          // buildSearchBar(),
          SizedBox(height: 15.rpx + max(20, kSafeTop)),
          QGTypeSwitchWidget(
              current: type,
              items: names,
              underline: true,
              fontSize: 16,
              maxFontSize: 16,
              alignment: MainAxisAlignment.spaceEvenly,
              onSwitch: onSwitchType),
        ],
      ),
    );
  }

  buildSearchBar() {
    return Stack(
      children: [
        Container(
          margin: EdgeInsets.only(
              top: 30 + max(20, kSafeTop), left: 15.rpx, right: 15.rpx),
          child: Container(
            padding: EdgeInsets.only(left: 10.rpx),
            height: 32.rpx,
            decoration: BoxDecoration(
              border: Border.all(width: 1.rpx, color: Color(0xFF111111)),
              borderRadius: BorderRadius.circular(6.rpx),
              color: Colors.transparent,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                QGImage(asset: "sale_search"),
                TextButton(
                  onPressed: onSearch,
                  child: Container(
                    child: Text(
                      '搜索',
                      style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: 12.rpx,
                          fontWeight: FontWeight.normal),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        buildTextField(),
      ],
    );
  }

  buildTextField() {
    return Positioned(
      left: 40,
      top: 33 + max(20, kSafeTop),
      right: 80,
      child: Container(
        height: 30.rpx,
        child: TextField(
            scrollPadding: EdgeInsets.zero,
            onChanged: (content) {
              if (content.isEmpty) {
                setState(() {});
              }
            },
            controller: controller,
            textInputAction: TextInputAction.done,
            cursorColor: Color(0xFF111111),
            style: TextStyle(
                color: Color(0xFF111111),
                fontSize: 12.rpx,
                fontWeight: FontWeight.bold),
            decoration: InputDecoration(
              hintText: "搜索藏品",
              hintStyle: TextStyle(
                color: Color(0xff999999),
                fontSize: 12.rpx,
              ),
              enabledBorder: InputBorder.none,
              focusedBorder: InputBorder.none,
            )),
      ),
    );
  }

  buildSwitchBar() {
    if (names.isEmpty) return Container();
   
    if (type == 0) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(vertical: 14.rpx),
        margin: EdgeInsets.only(left: 5.rpx),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
                child: 
                QGSwitchWidget(
                    index: subtype, items: names, onSwitch: onSwitchSubType)
                    ),
            type == 0
                ? GestureDetector(
                    onTap: onCategory,
                    child: Container(
                    alignment: Alignment.center,

                      padding: EdgeInsets.only(
                          left: 19.rpx,
                          // top: 6.rpx,
                          right: 10.rpx,
                           bottom: 32.rpx
                          ),
                      child: QGImage(asset: "nav_bulletin_active",width: 16.rpx),
                    ),
                  )
                : Container(),
          ],
        ),
      );
    }

    if (type == 1) {
      return Container(child: buildSort());
    }

    return Container( 
       padding: EdgeInsets.symmetric(horizontal: 10.rpx, vertical: 10.rpx),
      child: Row(mainAxisAlignment: MainAxisAlignment.center, children: []),
    );
  }

  buildSort() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 14.rpx),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          QGDrawerWidget(
            index: leveltype,
            items: ["等级排序", "版权品R", "版权品SR", "版权品SSR"],
            onSelect: onLevelSort,
          ),
          QGSortPriceWidget(
              current: sorttype, items: ["价格升序", "价格降序"], onSwitch: onSort),
        ],
      ),
    );
  }

  onSwitchType(index) {
    type = index;

    subtype = type == 0 ? 0 : 0;
    list = null;
    sorttype = 0;

    listURL = url_index_consignmentList;
    listKey = "list";
  

    if (type == 0 && User.isLogin) {
      tabURL = url_market_mySeriesList;
    } else {
      tabURL = url_index_seriesList;
    }

    if (mounted) setState(() {});
   loadTab();
  }

  onSwitchSubType(idx) {
    if (type == 0 && idx == 0) {
      if (!User.isLogin) {
        if (mounted) setState(() {});
        Navigator.of(context).pushNamed(PageLogin);
        return;
      }
    }

    subtype = idx;
    list = null;

    listURL = url_index_consignmentList;
    listKey = "list";

    if (mounted) setState(() {});
    onRefresh();
  }

  onLevelSort(int index) {
    sorttype = 2;
    leveltype = index;
    list = null;
    setState(() {});
    onRefresh();
  }

  onSort(int index) {
    sorttype = index;
    leveltype = 0;
    list = null;
    setState(() {});
    onRefresh();
  }

  onSearch() {
    unfocus(context);
    list = null;
    setState(() {});
    onRefresh();
  }

  onCategory() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }

    Navigator.of(context).pushNamed(PageTradeCategory);
  }

  toDetail(data) {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }

    switch (type) {
      case 0:
        Navigator.of(context)
            .pushNamed(PageTradeDetail, arguments: data["pid"] ?? "");
        break;
      case 1:
        var param = {"pid": data["pid"], "priceSort": "asc"};
        Network.post(url_market_collectionList, data: param).then((res) {
          if (!res.success) {
            return;
          }

          if (res.data["data"] is! List || res.data["data"].isEmpty) {
            return;
          }

          if (res.data["data"][0]["isOwner"] == 1) {
            toast("不能购买自己流转的藏品");
            return;
          }

          Navigator.of(context).pushNamed(PageTradeCopyrightNFTDetail,
              arguments: res.data["data"][0]["cid"] ?? "");
        });
        break;
      case 2:
        Navigator.of(context)
            .pushNamed(PageTradeDetail, arguments: data["pid"] ?? "");
        break;
    }
  }
}
